package cn.fintecher.gis.web;

import cn.fintecher.gis.entity.UploadFile;
import cn.fintecher.gis.exception.BadRequestException;
import cn.fintecher.gis.geoserver.GeoManagerService;
import cn.fintecher.gis.model.ParsingShpResults;
import cn.fintecher.gis.postgis.PostGISService;
import cn.fintecher.gis.service.UploadFileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * Created by ChenChang on 2017/12/26.
 */
@RestController
@RequestMapping("/api/uploadFile")
@Api(value = "文件上传", description = "文件上传")
public class UploadFileController {
    private final Logger log = LoggerFactory.getLogger(UploadFileController.class);
    @Autowired
    private UploadFileService uploadFileService;
    @Autowired
    private PostGISService postGISService;
    @Autowired
    private GeoManagerService geoManagerService;

    //
//    @ApiOperation(value = "testCheck", notes = "testCheck")
//    @GetMapping("/testCheck")
//    public ResponseEntity<Void> testCheck(@RequestParam String table,@RequestParam String qs) throws Exception {
//         postGISService.query(qs,table);
//        return ResponseEntity.ok().build();
//
//    }
    @ApiOperation(value = "测试导入shp", notes = "测试导入shp")
    @GetMapping("/testImportShp/{id}")
    public ResponseEntity<Void> testImportShp(@PathVariable String id) throws IOException {
        log.debug("REST request to get UploadFile : {}", id);

        ParsingShpResults result1 = postGISService.uploadShp(id);
        if (!result1.getIsSuccess()) {
            throw new BadRequestException("importShp", result1.getMessage());
        }
        ParsingShpResults result2 = geoManagerService.releaseLayer(id, result1.getCrs(), null, "");
        if (!result2.getIsSuccess()) {
            throw new BadRequestException( "importShp", result2.getMessage());
        }
        return ResponseEntity.ok().build();

    }

    @ApiOperation(value = "测试发布Style", notes = "测试发布Style")
    @GetMapping("/testImportStyle")
    public ResponseEntity<Void> testImportStyle() throws IOException {
        String body = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
                "<sld:StyledLayerDescriptor xmlns=\"http://www.opengis.net/sld\" xmlns:sld=\"http://www.opengis.net/sld\" xmlns:ogc=\"http://www.opengis.net/ogc\" xmlns:gml=\"http://www.opengis.net/gml\" version=\"1.0.0\">\n" +
                "    <sld:UserLayer>\n" +
                "        <sld:LayerFeatureConstraints>\n" +
                "            <sld:FeatureTypeConstraint/>\n" +
                "        </sld:LayerFeatureConstraints>\n" +
                "        <sld:UserStyle>\n" +
                "            <sld:Name>610602JSYDGZQ</sld:Name>\n" +
                "            <sld:Title/>\n" +
                "            <sld:FeatureTypeStyle>\n" +
                "                <sld:Name>group 0</sld:Name>\n" +
                "                <sld:FeatureTypeName>Feature</sld:FeatureTypeName>\n" +
                "                <sld:SemanticTypeIdentifier>generic:geometry</sld:SemanticTypeIdentifier>\n" +
                "                <sld:SemanticTypeIdentifier>colorbrewer:quantile:spectral</sld:SemanticTypeIdentifier>\n" +
                "                <sld:Rule>\n" +
                "                    <sld:Name>rule01</sld:Name>\n" +
                "                    <sld:Title>1..2503</sld:Title>\n" +
                "                    <ogc:Filter>\n" +
                "                        <ogc:And>\n" +
                "                            <ogc:PropertyIsGreaterThanOrEqualTo>\n" +
                "                                <ogc:PropertyName>bsm</ogc:PropertyName>\n" +
                "                                <ogc:Literal>1</ogc:Literal>\n" +
                "                            </ogc:PropertyIsGreaterThanOrEqualTo>\n" +
                "                            <ogc:PropertyIsLessThan>\n" +
                "                                <ogc:PropertyName>bsm</ogc:PropertyName>\n" +
                "                                <ogc:Literal>2503</ogc:Literal>\n" +
                "                            </ogc:PropertyIsLessThan>\n" +
                "                        </ogc:And>\n" +
                "                    </ogc:Filter>\n" +
                "                   <sld:PolygonSymbolizer>\n" +
                "                      <sld:Fill>\n" +
                "                   \t\t<CssParameter name=\"fill\">#FDAE61</CssParameter>\n" +
                "                        </sld:Fill>\n" +
                "                     </sld:PolygonSymbolizer>\n" +
                "                    <sld:PolygonSymbolizer>\n" +
                "                        <sld:Fill>\n" +
                "                            <GraphicFill>\n" +
                "                                <Graphic>\n" +
                "                                    <Mark>\n" +
                "                                        <WellKnownName>shape://slash</WellKnownName>\n" +
                "                                        <Stroke>\n" +
                "                                            <CssParameter name=\"stroke\">#00DD00</CssParameter>\n" +
                "                                            <CssParameter name=\"stroke-width\">1</CssParameter>\n" +
                "                                        </Stroke>\n" +
                "                                    </Mark>\n" +
                "                                </Graphic>\n" +
                "                            </GraphicFill>\n" +
                "                        </sld:Fill>\n" +
                "                        <sld:Stroke/>\n" +
                "                    </sld:PolygonSymbolizer>\n" +
                "                  <LineSymbolizer>\n" +
                "                    <Stroke>\n" +
                "                      <GraphicStroke>\n" +
                "                        <Graphic>\n" +
                "                          <Mark>\n" +
                "                            <WellKnownName>wkt://MULTILINESTRING((-0.25 -0.25, -0.125 -0.25), (0.125 -0.25, 0.25 -0.25), (-0.25 0.25, -0.125 0.25), (0.125 0.25, 0.25 0.25))</WellKnownName>\n" +
                "                            <Fill>\n" +
                "                              <CssParameter name=\"fill\">#0000ff</CssParameter>\n" +
                "                            </Fill>\n" +
                "                            <Stroke>\n" +
                "                              <CssParameter name=\"stroke\">#0000ff</CssParameter>\n" +
                "                              <CssParameter name=\"stroke-width\">1</CssParameter>\n" +
                "                            </Stroke>\n" +
                "                          </Mark>\n" +
                "                          <Size>6</Size>\n" +
                "                        </Graphic>\n" +
                "                      </GraphicStroke>\n" +
                "                    </Stroke>\n" +
                "                  </LineSymbolizer>\n" +
                "                    <sld:TextSymbolizer>\n" +
                "                        <sld:Label>农田</sld:Label>\n" +
                "                        <sld:Font>\n" +
                "                            <sld:CssParameter name=\"font-family\">\\u5B8B\\u4F53</sld:CssParameter>\n" +
                "                            <sld:CssParameter name=\"font-size\">16.0</sld:CssParameter>\n" +
                "                            <sld:CssParameter name=\"font-style\">normal</sld:CssParameter>\n" +
                "                            <sld:CssParameter name=\"font-weight\">normal</sld:CssParameter>\n" +
                "                        </sld:Font>\n" +
                "                        <sld:LabelPlacement>\n" +
                "                            <sld:PointPlacement>\n" +
                "                                <sld:AnchorPoint>\n" +
                "                                    <sld:AnchorPointX>0.5</sld:AnchorPointX>\n" +
                "                                    <sld:AnchorPointY>0.5</sld:AnchorPointY>\n" +
                "                                </sld:AnchorPoint>\n" +
                "                                <sld:Displacement>\n" +
                "                                    <sld:DisplacementX>0.0</sld:DisplacementX>\n" +
                "                                    <sld:DisplacementY>0.0</sld:DisplacementY>\n" +
                "                                </sld:Displacement>\n" +
                "                            </sld:PointPlacement>\n" +
                "                        </sld:LabelPlacement>\n" +
                "                        <sld:Fill>\n" +
                "                            <sld:CssParameter name=\"fill\">#000000</sld:CssParameter>\n" +
                "                        </sld:Fill>\n" +
                "                    </sld:TextSymbolizer>\n" +
                "                </sld:Rule>\n" +
                "                <sld:Rule>\n" +
                "                    <sld:Name>rule02</sld:Name>\n" +
                "                    <sld:Title>2503..5005</sld:Title>\n" +
                "                    <ogc:Filter>\n" +
                "                        <ogc:And>\n" +
                "                            <ogc:PropertyIsGreaterThanOrEqualTo>\n" +
                "                                <ogc:PropertyName>bsm</ogc:PropertyName>\n" +
                "                                <ogc:Literal>2503</ogc:Literal>\n" +
                "                            </ogc:PropertyIsGreaterThanOrEqualTo>\n" +
                "                            <ogc:PropertyIsLessThan>\n" +
                "                                <ogc:PropertyName>bsm</ogc:PropertyName>\n" +
                "                                <ogc:Literal>5005</ogc:Literal>\n" +
                "                            </ogc:PropertyIsLessThan>\n" +
                "                        </ogc:And>\n" +
                "                    </ogc:Filter>\n" +
                "                    <sld:PolygonSymbolizer>\n" +
                "                        <sld:Fill>\n" +
                "                            <sld:CssParameter name=\"fill\">#FDAE61</sld:CssParameter>\n" +
                "                            <sld:CssParameter name=\"fill-opacity\">0.5</sld:CssParameter>\n" +
                "                        </sld:Fill>\n" +
                "                        <sld:Stroke/>\n" +
                "                    </sld:PolygonSymbolizer>\n" +
                "                    <sld:TextSymbolizer>\n" +
                "                        <sld:Label>\n" +
                "                            <ogc:PropertyName>bsm</ogc:PropertyName>\n" +
                "                        </sld:Label>\n" +
                "                        <sld:Font>\n" +
                "                            <sld:CssParameter name=\"font-family\">\\u5B8B\\u4F53</sld:CssParameter>\n" +
                "                            <sld:CssParameter name=\"font-size\">16.0</sld:CssParameter>\n" +
                "                            <sld:CssParameter name=\"font-style\">normal</sld:CssParameter>\n" +
                "                            <sld:CssParameter name=\"font-weight\">normal</sld:CssParameter>\n" +
                "                        </sld:Font>\n" +
                "                        <sld:LabelPlacement>\n" +
                "                            <sld:PointPlacement>\n" +
                "                                <sld:AnchorPoint>\n" +
                "                                    <sld:AnchorPointX>0.5</sld:AnchorPointX>\n" +
                "                                    <sld:AnchorPointY>0.5</sld:AnchorPointY>\n" +
                "                                </sld:AnchorPoint>\n" +
                "                                <sld:Displacement>\n" +
                "                                    <sld:DisplacementX>0.0</sld:DisplacementX>\n" +
                "                                    <sld:DisplacementY>0.0</sld:DisplacementY>\n" +
                "                                </sld:Displacement>\n" +
                "                            </sld:PointPlacement>\n" +
                "                        </sld:LabelPlacement>\n" +
                "                        <sld:Fill>\n" +
                "                            <sld:CssParameter name=\"fill\">#000000</sld:CssParameter>\n" +
                "                        </sld:Fill>\n" +
                "                    </sld:TextSymbolizer>\n" +
                "                </sld:Rule>\n" +
                "                <sld:Rule>\n" +
                "                    <sld:Name>rule03</sld:Name>\n" +
                "                    <sld:Title>5005..7506</sld:Title>\n" +
                "                    <ogc:Filter>\n" +
                "                        <ogc:And>\n" +
                "                            <ogc:PropertyIsGreaterThanOrEqualTo>\n" +
                "                                <ogc:PropertyName>bsm</ogc:PropertyName>\n" +
                "                                <ogc:Literal>5005</ogc:Literal>\n" +
                "                            </ogc:PropertyIsGreaterThanOrEqualTo>\n" +
                "                            <ogc:PropertyIsLessThan>\n" +
                "                                <ogc:PropertyName>bsm</ogc:PropertyName>\n" +
                "                                <ogc:Literal>7506</ogc:Literal>\n" +
                "                            </ogc:PropertyIsLessThan>\n" +
                "                        </ogc:And>\n" +
                "                    </ogc:Filter>\n" +
                "                    <sld:PolygonSymbolizer>\n" +
                "                        <sld:Fill>\n" +
                "                            <sld:CssParameter name=\"fill\">#FFFFBF</sld:CssParameter>\n" +
                "                            <sld:CssParameter name=\"fill-opacity\">0.5</sld:CssParameter>\n" +
                "                        </sld:Fill>\n" +
                "                    </sld:PolygonSymbolizer>\n" +
                "                </sld:Rule>\n" +
                "                <sld:Rule>\n" +
                "                    <sld:Name>rule04</sld:Name>\n" +
                "                    <sld:Title>7506..10007</sld:Title>\n" +
                "                    <ogc:Filter>\n" +
                "                        <ogc:And>\n" +
                "                            <ogc:PropertyIsGreaterThanOrEqualTo>\n" +
                "                                <ogc:PropertyName>bsm</ogc:PropertyName>\n" +
                "                                <ogc:Literal>7506</ogc:Literal>\n" +
                "                            </ogc:PropertyIsGreaterThanOrEqualTo>\n" +
                "                            <ogc:PropertyIsLessThan>\n" +
                "                                <ogc:PropertyName>bsm</ogc:PropertyName>\n" +
                "                                <ogc:Literal>10007</ogc:Literal>\n" +
                "                            </ogc:PropertyIsLessThan>\n" +
                "                        </ogc:And>\n" +
                "                    </ogc:Filter>\n" +
                "                    <sld:PolygonSymbolizer>\n" +
                "                        <sld:Fill>\n" +
                "                            <sld:CssParameter name=\"fill\">#ABDDA4</sld:CssParameter>\n" +
                "                            <sld:CssParameter name=\"fill-opacity\">0.5</sld:CssParameter>\n" +
                "                        </sld:Fill>\n" +
                "                    </sld:PolygonSymbolizer>\n" +
                "                </sld:Rule>\n" +
                "                <sld:Rule>\n" +
                "                    <sld:Name>rule05</sld:Name>\n" +
                "                    <sld:Title>10007..12507</sld:Title>\n" +
                "                    <ogc:Filter>\n" +
                "                        <ogc:And>\n" +
                "                            <ogc:PropertyIsGreaterThanOrEqualTo>\n" +
                "                                <ogc:PropertyName>bsm</ogc:PropertyName>\n" +
                "                                <ogc:Literal>10007</ogc:Literal>\n" +
                "                            </ogc:PropertyIsGreaterThanOrEqualTo>\n" +
                "                            <ogc:PropertyIsLessThanOrEqualTo>\n" +
                "                                <ogc:PropertyName>bsm</ogc:PropertyName>\n" +
                "                                <ogc:Literal>12507</ogc:Literal>\n" +
                "                            </ogc:PropertyIsLessThanOrEqualTo>\n" +
                "                        </ogc:And>\n" +
                "                    </ogc:Filter>\n" +
                "                    <sld:PolygonSymbolizer>\n" +
                "                        <sld:Fill>\n" +
                "                            <sld:CssParameter name=\"fill\">#2B83BA</sld:CssParameter>\n" +
                "                            <sld:CssParameter name=\"fill-opacity\">0.5</sld:CssParameter>\n" +
                "                        </sld:Fill>\n" +
                "                    </sld:PolygonSymbolizer>\n" +
                "                </sld:Rule>\n" +
                "            </sld:FeatureTypeStyle>\n" +
                "        </sld:UserStyle>\n" +
                "    </sld:UserLayer>\n" +
                "</sld:StyledLayerDescriptor>\n";
        geoManagerService.releaseStyle("test002", body, "");
        return ResponseEntity.ok().build();

    }
    @ApiOperation(value = "文件上传", notes = "文件上传")
    @PostMapping("/upload")
    public ResponseEntity<UploadFile> fileUpload(@RequestParam("file") MultipartFile file) throws IOException {
        return uploadFileService.fileUpload(file);
    }

    @ApiOperation(value = "通过文件名下载文件", notes = "通过文件名下载文件")
    @GetMapping("/getFile/{fileName}")
    public void getFile(@PathVariable String fileName, HttpServletResponse response) {
        log.debug("开始下载文件");
        File file = uploadFileService.findOneFileByName(fileName);
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
        ServletOutputStream out;
        try {
            FileInputStream inputStream = new FileInputStream(file);
            out = response.getOutputStream();
            int b = 0;
            byte[] buffer = new byte[1024];
            while (b != -1) {
                b = inputStream.read(buffer);
                out.write(buffer, 0, b);
            }
            inputStream.close();
            out.close();
            out.flush();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @ApiOperation(value = "按ID查询", notes = "按ID查询")
    @GetMapping("/getUploadFile/{id}")
    public ResponseEntity<UploadFile> getUploadFile(@PathVariable String id) {
        log.debug("REST request to get UploadFile : {}", id);
        UploadFile uploadFile = uploadFileService.findOne(id);

        return Optional.ofNullable(uploadFile)
                .map(result -> new ResponseEntity<>(
                        result,
                        HttpStatus.OK))
                .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
    }


    @GetMapping("/getUploadFileList/{ids}")
    @ApiOperation(value = "按ID查询", notes = "按ID查询")
    public ResponseEntity<List<UploadFile>> getUploadFileList(@PathVariable String ids) {
        log.debug("REST request to get UploadFile : {}", ids);
        String[] files = ids.split(",");
        List<UploadFile> list = new ArrayList<>();
        for (int i = 0; i < files.length; i++) {
            UploadFile uploadFile = uploadFileService.findOne(files[i].toString());
            list.add(uploadFile);
        }
        return Optional.ofNullable(list)
                .map(result -> new ResponseEntity<>(
                        result,
                        HttpStatus.OK))
                .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
    }


}
